<template>
    <div class="store-details">
        <div class="store-search">
            <el-form :model="searchContent" ref="searchFrom" :inline="true">
                <el-form-item label="统计时间">
                    <el-date-picker
                        type="daterange"
                        :clearable="false"
                        v-model="dateInterval"
                        value-format="yyyy-MM-dd"
                        :picker-options="pickerOptions"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        @change="handleChangeTime">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="访问来源">
                    <el-select v-model="searchContent.webpage" placeholder="请选择" clearable>
                        <el-option
                            v-for="item in webpageType"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="统计维度">
                    <el-select v-model="searchContent.dimension" @change="handleDimensionChange" placeholder="请选择">
                        <el-option
                            v-for="item in dimensionType"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属品线" v-if="searchContent.dimension == 2">
                    <el-select v-model="searchContent.depart_id" @change='handleDepartChange' placeholder="全部">
                        <el-option
                            v-for="item in departType"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item 
                    label="店铺选择"
                    v-if="searchContent.dimension == 1 || (searchContent.dimension == 2 && searchContent.depart_id != '')">
                    <el-select
                        v-model="searchContent.store_id"
                        filterable
                        clearable
                        remote
                        reserve-keyword
                        autocomplete
                        placeholder="选择店铺、搜索店铺"
                        :remote-method="handleRemote"
                        :loading="loading"
                        @focus="handleFocus">
                        <el-option
                            v-for="item in storeLists"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button type="primary" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="store-charts">
            <div class="charts-box">
                <div class="charts-header">
                    <div class="charts-title">流量趋势</div>
                    <div class="charts-date-type">
                    </div>
                </div>
                <div class="charts-type">
                    <el-checkbox v-for="item in dataTypeArr" :key="item.value" v-model="item.checked" :label="`${item.label}: ${item.total}`" border @change='handleChangeType'></el-checkbox>
                </div>
                <div class="charts-content">
                    <ChartsLine :dataArr="dataArr" :showParticleSize="false" container="c1"></ChartsLine>
                </div>
            </div>
            <div class="charts-box">
                <div class="charts-header">
                    <div class="charts-title">流量明细</div>
                </div>
                <div class="charts-content" style="padding-top: 0;">
                    <Lists :searchContent="searchContents"/>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { dateFormatter, formatterNum } from '@/common/js/util'
import ChartsLine from './charts-line'
import Lists from './lists'

export default {
    components: { ChartsLine, Lists },
    data() {
        return {
            searchContent: {},         // charts 搜索字段
            searchContents: {},        // 列表组件搜索字段
            dimensionType: [           // 统计维度
				{label: '单店', value: 1},
				{label: '品线', value: 2},
            ],
            webpageType: [                // 访问来源
				{label: '经销商首页', value: '经销商首页'},
				{label: '新车团购', value: '新车团购首页'},
				{label: '售后团购', value: '售后团购首页'},
				{label: '保养预约', value: '保养预约'},
				{label: '预约试驾', value: '预约试驾'},
				{label: '特惠好车', value: '特惠好车'},
				{label: '在线支付', value: '在线支付'},
				{label: '一键救援', value: '一键救援'},
				{label: '直播', value: '直播'},
				{label: '在线评估', value: '在线评估'}
            ],
            departType: [],            // 品线类型数组
            storeLists: [],            // 店铺数据
            loading: false,            // 是否处于远程加载店铺数据中
            pickerMinDate: null,
            pickerOptions: {
                onPick: ({ maxDate, minDate }) => {
                    this.pickerMinDate = minDate
                },
                disabledDate: time => {
                    const intervalTtime = 24 * 30 * 24 * 3600 * 1000; // 仅支持选择24个月范围
                    const currDate = this.pickerMinDate ? new Date(this.pickerMinDate) : new Date()
                    const minTime = currDate.getTime() - intervalTtime;
                    const maxTime = currDate.getTime() + intervalTtime;
                    let date = new Date(), dateTime = Date.now(), nowMonth = true;
                    // nowMonth = time.getFullYear() <= date.getFullYear() && time.getMonth() < date.getMonth(); // 不支持当月
                    // dateTime -= 8.64e7; // 不支持当日
                    return time.getTime() > dateTime || time.getTime() < minTime || time.getTime() > maxTime || !nowMonth
                }
            },
            dataTypeArr: [
                {label: '访问次数', value: 1, checked: true, total: 0},
                {label: '访问人数', value: 2, checked: true, total: 0}
            ],
            dataArr: {
                markerEnabled: true,
                series:  []
            },
            dateDataType: [],
            dateInterval: [] // 默认时间为近半个月
        }
    },
    methods: {
        // 数据初始化
        init() {
            // 取最近15天日期(不含当天)
            const date = new Date()
            date.setDate(date.getDate() - 1)
            const end = dateFormatter("YYYY-MM-DD", date.getTime())
            date.setDate(date.getDate() - 14)
            const begin = dateFormatter("YYYY-MM-DD", date.getTime())
            this.dateInterval = [begin, end]

            // 默认搜索属性
            this.searchContent = {
                begin_date: begin,    // 开始时间
                end_date: end,        // 结束时间 
                dimension: 1,         // 统计维度
                store_id_in: '',      // 店铺ID数组
                store_id: '',         // 店铺ID
                depart_id: '',        // 品线ID
                webpage: ''           // 来源 
            }
            this.storeLists = []      // 店铺列表
        },
        // 日期切换
        handleChangeTime(val) {
            if(val) {
                Reflect.set(this.searchContent, "begin_date", val[0])
                Reflect.set(this.searchContent, "end_date", val[1])
            } else {
                Reflect.set(this.searchContent, "begin_date", null)
                Reflect.set(this.searchContent, "end_date", null)
            }
        },
        // 获取品线数据
        getDepart() {
            this.$http.post("/admin/depart/index.php?act=departManage&op=groupList", {depart_id: 600}) // 600 为集团ID
            .then( res => {
                if (res.code == 1 && res.data.length > 0) {
                    this.departType = res.data.map(item =>({
                        depart_id: item.depart_id,
                        store_ids: item.store_ids,
                        label: item.depart_name, 
                        value: item.depart_id
                    }));
                } else {
                    this.$message.error("品线数据获取失败!");
                }
            })
        },
        // 维度选择
        handleDimensionChange() {
            this.storeLists = []
            this.searchContent.store_id = ''
            this.searchContent.store_id_in = ''
            this.searchContent.depart_id = ''
        },
        // 品线选择
        handleDepartChange(val) {
            const depart = this.departType.find(depart => depart.depart_id == val)
            this.searchContent.store_id_in = depart.store_ids.join(",")
            this.searchContent.store_id = ''
            this.getStoreList('', this.searchContent.store_id_in)
        },
        // 店铺表单获得焦点
        handleFocus(){
            if(this.storeLists.length <= 0 && this.searchContent.dimension == 1) {
                this.getStoreList();
            }
        },
        // 店铺搜索
        handleRemote(keywords) {
            this.getStoreList(keywords);
        },
        // 搜索
        handleSearch() {
            this.getChartsData()
        },
        // 搜索重置
        handleReset() {
            this.$refs.searchFrom.resetFields();
            this.init()
            this.getChartsData()
        },
        // 获取店铺列表数据
        getStoreList(storeName = '', store_id_in = null) {
            this.loading = true
            const data = {
                page: 1,
                eachNum: 200,
                storeName,
                loadingclose: false,
                storeUserName: '',
                type: 'filter_not_yt'
            };
            if(store_id_in) {
                data.store_id_in = store_id_in
            }
            this.$http.post('/admin/store/index.php?act=storeManage&op=getStoreList', data).then(res => {
                this.loading = false
                if (res.code == 1) {
                    this.storeLists = res.data && res.data.list && 
                    res.data.list.map(item => ({
                        value: item.store_id,
                        label: item.store_name
                    })) || []
                } else {
                    this.storeLists = [];
                    res.msg && this.$message.error(res.msg)
                }
            })
        },
        // charts图例选择
        handleChangeType(val) {
            this.dataTypeArr.forEach((item, index) => {
                this.dataArr.series[index].visible = item.checked
            })
        },
        // 获取charts数据+
        getChartsData() {
            this.searchContents = {...this.searchContent}
            this.searchContent.data_type = 2
            const datas = { ...this.searchContent }
            this.$http.get('/admin/yt_car/index.php?act=statistic&op=storeFlowTrend', {params: datas})
            .then(res => {
                if(res.code == 1) {
                    const pv = res.data.graph.pv || []
                    const uv = res.data.graph.uv || [];
                    this.dataArr.series = [{
                        name: '访问次数',
                        color: '#1890FF',
                        tooltip: {
                            valueSuffix: '次'
                        },
		                data: pv,
                        visible: this.dataTypeArr[0].checked
                    },{
                        name: '访问人数',
                        color: '#5CAF34',
                        tooltip: {
                            valueSuffix: '人'
                        },
		                data: uv,
                        visible: this.dataTypeArr[1].checked // 默认不显示
                    }];
                    this.dataTypeArr[0].total = formatterNum(res.data.pv) + '次'
                    this.dataTypeArr[1].total = formatterNum(res.data.uv) + '人'
                } else {
                    this.$message.error(res.msg);
                }
            })
        }
    },
    created() {
        this.init()
        this.getDepart()
        this.getChartsData()
    },
    mounted() {
        // 清除 el-main 的内边距
        const elMain = document.querySelector(".el-main")
        if (elMain) elMain.style.padding = '0px'
        this.$store.dispatch('setPageCenterTitle', '元通汽车官方平台BI报表');
    },
    destroyed() {
        const elMain = document.querySelector(".el-main")
        if (elMain) elMain.style.padding = ''
        this.$store.dispatch('setPageCenterTitle', '');
    }
}
</script>
<style lang="scss" scoped>
    @import url('~@/common/scss/charts-public.scss'); 
    .store-details {
        background: #f6f6f6;
        width: 100%;
        height: 100%;
        padding: 16px;
        display: flex;
        align-items: space-between;
        flex-direction: column;
        justify-content: flex-start;
    }
    .store-search {
        /deep/.el-date-editor .el-range-separator {
            width: 8%;
        }
        /deep/.el-form-item__label {
            padding-right: 8px;
        }
    }
    .store-charts {
        height: calc(100% - 30px);
    }
    .charts-box {
        background: #fff;
        box-shadow: 0px 0px 10px #ddd;
        box-sizing: border-box;
        height: 49.1%;
        margin: 0 0 15px;
        position: relative;
        flex-grow: 1;
        .charts-header {
            border: 0;
        }
        .charts-type {
            position: absolute;
            right: 20px;
            top: 19px;
            .el-checkbox {
                margin-right: 5px;
                /deep/.el-checkbox__label {
                    padding-left: 5px;
                    vertical-align: 1px;
                }
            }
        }
        .charts-content {
            padding-top: 12px;
            padding-bottom: 4px;
        }
    }
</style>